package Servlet;

import Dao.PostDao;
import Dao.UserDao;
import Vo.Post;
import Vo.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

@WebServlet(name = "postServlet", value = "/postServlet")
public class postServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("成功连接到数据库");
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/html;charset=utf-8");
        HttpSession session=request.getSession();
//        String Uid=request.getParameter("Uid");
        User user=(User)session.getAttribute("user");
        HashMap allpost=(HashMap) session.getAttribute("allpost");
        UserDao userDao =new UserDao();
        String title=request.getParameter("title");
        String content=request.getParameter("content");
        Date  date=new Date();
        String dateStr =new SimpleDateFormat().format(new Date());
        String Pid=Integer.toString(new Random().nextInt(1000)+1000);
        PostDao postDao=new PostDao();
        try {
            if(title!=null) postDao.postMessage(Pid,user.getUid(),title,content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Post post=new Post();
        post.setPid(Pid);
        post.setTitle(title);
        post.setTitlepic("0");
        post.setCreatedtime(dateStr);
        post.setTabid("0");
        post.setUid(user.getUid());
        post.setUsername(user.getUsername());
        post.setType(0);
        post.setTags("0");
        post.setHits(0);
        post.setContent(content);
        allpost.put(Pid,post);
        response.sendRedirect("home.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);

    }
}
